package hc.bre.rest.admin

import org.apache.shiro.SecurityUtils
import org.apache.shiro.crypto.SecureRandomNumberGenerator
import org.apache.shiro.crypto.hash.Sha256Hash
import org.apache.shiro.subject.Subject

class AuthUtil {
	static SecureRandomNumberGenerator saltGenerator = new SecureRandomNumberGenerator();

	static public String generateSalt() {
		return saltGenerator.nextBytes().toHex();
	}

	static public String encriptPassword(String password, String salt) {
		Sha256Hash sha256 = new Sha256Hash(password, salt,2);
		return sha256.toBase64();
	};

	static public void updatePassword(BreUser user, String newPwd) {
		user.salt = AuthUtil.generateSalt();
		user.password = AuthUtil.encriptPassword(newPwd, user.salt)
	}

	static public <T> T permit(String rpath,BrePermission permission, Closure<T> closure) {
		Subject subject = SecurityUtils.getSubject();

		String project = hc.Util.rpathPrjectCode(rpath);
		String accessCode = hc.Util.rpathInProject(rpath);

		DEVMODE || subject.checkPermission("${project}:${permission}:${accessCode}");

		return closure.call();
	};

	static public boolean isPermitted(String rpath,BrePermission permission) {
		Subject subject = SecurityUtils.getSubject();
		String project = hc.Util.rpathPrjectCode(rpath);
		String accessCode = hc.Util.rpathInProject(rpath)

		return DEVMODE || subject.isPermitted("${project}:${permission}:${accessCode}");
	}

	static public boolean isFuncPermitted(BrePermission permission) {
		if(permission==null) return true;

		Subject subject = SecurityUtils.getSubject();

		return DEVMODE || subject.isPermitted("@func:${permission}");
	};

	static public <T> T permit(BrePermission funcPermission, Closure<T> closure) {
		Subject subject = SecurityUtils.getSubject();
		
		DEVMODE || subject.checkPermission("@func:${funcPermission}");
		
		return closure.call();
	};

	static public BreUser user() {
		Subject subject = SecurityUtils.getSubject();
		BreUser usr = (BreUser) subject.getPrincipal();

		if(DEVMODE && usr == null) usr = new BreUser(id:-1,code:'dev',name:'dev');

		return usr;
	}

	static public String userText() {
		BreUser user = user();
		return user?"${user.id}:${user.code}:${user.name}":'';
	}

	static boolean DEVMODE = true;
}